package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shop_srv/cache"
	"shop_srv/models"
	"time"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchGoodsLogic {
	return &SearchGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchGoodsLogic) SearchGoods(in *shop.SearchGoodsRequest) (*shop.SearchGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var g models.Goods
	key := fmt.Sprintf("goods_list_%d", in.GoodsId)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()

	if cacheData == "" {
		models.DB.Where("id=?", in.GoodsId).Find(&g)
		jsonData, _ := json.Marshal(g)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*5)
	} else {
		err := json.Unmarshal([]byte(cacheData), &g)
		if err != nil {
			return nil, err
		}
	}

	return &shop.SearchGoodsResponse{
		GoodsId: int64(g.ID),
		Title:   g.Title,
		Price:   float32(g.Price),
		Stock:   g.Stock,
		Status:  g.GoodsStatus,
	}, nil
}
